<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :inline="true"
      :model="queryParams"
      label-width="68px"
    >
      <el-form-item label="规则名称" prop="name">
        <el-input
          v-model="queryParams.name"
          clearable
          placeholder="请输入规则名称"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="规则编号" prop="code">
        <el-input
          v-model="queryParams.code"
          clearable
          placeholder="请输入规则编号"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="运行状态" prop="runState">
        <el-select
          v-model="queryParams.runState"
          clearable
          placeholder="运行状态"
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.iot_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          icon="el-icon-search"
          size="mini"
          type="primary"
          @click="handleQuery"
          >搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          icon="el-icon-plus"
          plain
          size="mini"
          type="primary"
          @click="handleAdd"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          :disabled="multiple"
          icon="el-icon-delete"
          plain
          size="mini"
          type="danger"
          @click="handleDelete"
          >删除
        </el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表格区域 -->
    <el-table
      v-loading="loading"
      :data="ruleList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column align="center" type="selection" width="55" />
      <el-table-column align="center" label="规则名称" prop="name" />
      <el-table-column align="center" label="规则编号" prop="code" />
      <el-table-column
        align="center"
        label="生效时间类型"
        prop="takeEffectType"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.iot_rule_time_type"
            :value="scope.row.takeEffectType"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="触发类型" prop="triggerType">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.iot_rule_trigger_type"
            :value="scope.row.triggerType"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="运行状态" prop="runState">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.iot_state"
            :value="scope.row.runState"
          />
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="创建时间"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        class-name="small-padding fixed-width"
        label="操作"
      >
        <template slot-scope="scope">
          <el-button
            icon="el-icon-view"
            size="mini"
            type="text"
            @click="handleDetail(scope.row)"
            >详情
          </el-button>
          <el-button
            icon="el-icon-edit"
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            >修改
          </el-button>
          <el-button
            icon="el-icon-delete"
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :limit.sync="queryParams.pageSize"
      :page.sync="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <!-- 添加或修改联动规则对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="规则名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入规则名称" />
        </el-form-item>
        <el-form-item label="规则编号" prop="code">
          <el-input v-model="form.code" placeholder="请输入规则编号" />
        </el-form-item>
        <el-form-item label="生效时间类型" prop="takeEffectType">
          <el-select
            v-model="form.takeEffectType"
            placeholder="请选择生效时间类型"
          >
            <el-option
              v-for="dict in dict.type.iot_rule_time_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="生效时间范围"
          prop="timeRange"
          v-if="form.takeEffectType === 'appoint'"
        >
          <div style="display: flex; align-items: center">
            <el-time-picker
              is-range
              v-model="takeEffectTimeForm"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              placeholder="选择时间范围"
              format="HH:mm"
              value-format="HH:mm"
              default-time="00:00"
            >
            </el-time-picker>
          </div>
        </el-form-item>
        <el-form-item
          label="生效日期集合"
          prop="takeEffectWeeks"
          v-if="form.takeEffectType === 'appoint'"
        >
          <el-checkbox-group v-model="form.takeEffectWeeks">
            <el-checkbox label="周一">周一</el-checkbox>
            <el-checkbox label="周二">周二</el-checkbox>
            <el-checkbox label="周三">周三</el-checkbox>
            <el-checkbox label="周四">周四</el-checkbox>
            <el-checkbox label="周五">周五</el-checkbox>
            <el-checkbox label="周六">周六</el-checkbox>
            <el-checkbox label="周日">周日</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item
          label="生效日期"
          prop="effectiveDate"
          v-if="form.takeEffectType === 'appoint'"
        >
          <el-date-picker
            v-model="effectiveDateForm"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            placeholder="选择日期范围"
          />
        </el-form-item>
        <el-form-item label="触发类型" prop="triggerType">
          <el-select v-model="form.triggerType" placeholder="请选择触发类型">
            <el-option
              v-for="dict in dict.type.iot_rule_trigger_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="运行状态" prop="runState">
          <el-radio-group v-model="form.runState">
            <el-radio
              v-for="dict in dict.type.iot_state"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRule,
  getRule,
  delRule,
  addRule,
  updateRule,
} from "@/api/system/iot/rule";

export default {
  name: "Rule",
  dicts: ["iot_state", "iot_rule_time_type", "iot_rule_trigger_type"],
  data() {
    return {
      effectiveDateForm: [],
      takeEffectTimeForm: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 联动规则表格数据
      ruleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        code: undefined,
        runState: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "规则名称不能为空", trigger: "blur" },
        ],
        code: [
          { required: true, message: "规则编号不能为空", trigger: "blur" },
        ],
        takeEffectType: [
          {
            required: true,
            message: "生效时间类型不能为空",
            trigger: "change",
          },
        ],
        triggerType: [
          { required: true, message: "触发类型不能为空", trigger: "change" },
        ],
        runState: [
          { required: true, message: "运行状态不能为空", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询联动规则列表 */
    getList() {
      this.loading = true;
      listRule(this.queryParams).then((response) => {
        this.ruleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        ruleId: undefined,
        name: undefined,
        code: undefined,
        takeEffectType: undefined,
        effectiveDate: undefined,
        takeEffectWeeks: [],
        triggerType: undefined,
        runState: "0",
        takeEffectTim: undefined,
        remark: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.ruleId);
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加联动规则";
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      const ruleId = row.ruleId;
      this.$router.push({ path: `/system/iot/rule/detail/${ruleId}` });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ruleId = row.ruleId || this.ids;
      getRule(ruleId).then((response) => {
        this.form = response.data;
        // 将逗号分隔的字符串转换为数组
        if (this.form.takeEffectWeeks) {
          this.form.takeEffectWeeks = this.form.takeEffectWeeks.split(",");
        }
        // 解析生效时间范围
        if (this.form.takeEffectTime) {
          const [start, end] = this.form.takeEffectTime.split("至");
          this.takeEffectTimeForm = [start, end];
        } else {
          this.takeEffectTimeForm = ["00:00", "0:00"];
        }
        // 解析生效日期范围
        if (this.form.effectiveDate) {
          const [startDate, endDate] = this.form.effectiveDate.split("至");
          this.effectiveDateForm = [startDate, endDate];
        }
        this.open = true;
        this.title = "修改联动规则";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // 格式化生效时间范围
          if (this.takeEffectTimeForm && this.takeEffectTimeForm.length === 2) {
            const startTime = this.takeEffectTimeForm[0];
            const endTime = this.takeEffectTimeForm[1];
            this.form.takeEffectTime = `${startTime}至${endTime}`;
          }

          // 格式化生效日期范围
          if (this.effectiveDateForm && this.effectiveDateForm.length === 2) {
            const startDate = this.effectiveDateForm[0];
            const endDate = this.effectiveDateForm[1];
            this.form.effectiveDate = `${startDate}至${endDate}`;
          }

          // 将数组转换为逗号分隔的字符串
          if (
            this.form.takeEffectWeeks &&
            Array.isArray(this.form.takeEffectWeeks)
          ) {
            this.form.takeEffectWeeks = this.form.takeEffectWeeks.join(",");
          }
          if (this.form.ruleId != undefined) {
            updateRule(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRule(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ruleIds = row.ruleId || this.ids;
      this.$modal
        .confirm("是否确认删除联动规则的数据项？")
        .then(function () {
          return delRule(ruleIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>
